package vn.csp.gameportal;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import vn.csp.congcu.json.JSONParser;
import vn.csp.gameportal.R;
import vn.csp.util.ThongSo;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;

public class FragmentBest extends SherlockListFragment {
	
	 @Override
		public void onCreate(Bundle savedInstanceState) {
			layDuLieu();// nếu muốn mỗi lần load lại tab cập nhập lại list view thì gọi anh này
			super.onCreate(savedInstanceState);
		}
	    @Override
		  public void onListItemClick(ListView l, View v, int position, long id) {
		  	  Intent i = new Intent(getActivity().getApplicationContext(), GameDownload.class);
		  	  Bundle bundle = new Bundle();
		  	  bundle.putSerializable("ThongTinGameHayNhat", (Serializable) danhSachGameHayNhat.get(position));
			  i.putExtras(bundle);
			  startActivity(i);
		  }
	    //Nếu muốn mỗi lần load tab cập nhật lại thông tin thì override phương thức này
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			return super.onCreateView(inflater, container, savedInstanceState);
		}
		/** Danh sách game mới nhất ./. */
		List<ThongTinGame> danhSachGameHayNhat = new ArrayList<ThongTinGame>();
		public void layDuLieu() {
			new Thread(){
				@Override
				public void run() {
					JSONParser jsonParser = new JSONParser();
			        try {
			        	ThongSo thongSo = new ThongSo();
			        	JSONObject jsonObject = jsonParser.getJSONFromUrl(thongSo.URL,thongSo.CODE_PHP,ThongSo.YEU_CAU.GAME_HAY_NHAT.toString());
			        	JSONArray androidArray = jsonObject.getJSONArray("JSONResponse");
			        	for (int i = 0; i < androidArray.length(); i++) {
			        		danhSachGameHayNhat.add(new ThongTinGame(androidArray.getJSONObject(i).getString("TTG_ID"), 
		    				androidArray.getJSONObject(i).getString("TTG_TEN_GAME"), 
		    				androidArray.getJSONObject(i).getString("TTG_ICON"), 
		    				androidArray.getJSONObject(i).getString("TTG_LUOT_XEM"), 
		    				androidArray.getJSONObject(i).getString("TTG_LUOT_TAI"), 
		    				androidArray.getJSONObject(i).getString("TTG_DUONG_DAN"), 
		    				androidArray.getJSONObject(i).getString("TLG_TEN_THE_LOAI"),
		    				androidArray.getJSONObject(i).getString("DG_SODIEM"),
		    				androidArray.getJSONObject(i).getString("TTG_NOI_DUNG_MO_TA")
	    				));
						}
			        	Message m = myHandler.obtainMessage();
						myHandler.sendMessage(m);
					} catch (Exception e) {
						Message m = myHandler.obtainMessage();
						Bundle b = new Bundle();
						b.putString("thong_diep_loi", "Vui lòng kiểm tra kết nối.");
						m.setData(b);
						myHandler.sendMessage(m);
					}
				}
			}.start();
		}
		Handler myHandler = new Handler() {
			public void handleMessage (Message m) {
				String thong_diep_loi = m.getData().getString("thong_diep_loi");
				if(thong_diep_loi!=null){
					Toast.makeText(getActivity().getApplicationContext(),thong_diep_loi, Toast.LENGTH_SHORT).show();
				}else{
					if (!danhSachGameHayNhat.isEmpty()){
						List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
						//http://wptrafficanalyzer.in/blog/android-listfragment-with-images-and-text-using-android-support-library/
						int count = 0;
						Enumeration<ThongTinGame>  e = Collections.enumeration(danhSachGameHayNhat);
						while(e.hasMoreElements()){
							ThongTinGame gameMoiNhat = e.nextElement();
							String x = gameMoiNhat.getTTG_DUONG_DAN();
				            HashMap<String, String> hm = new HashMap<String,String>();
				            hm.put("icon", Integer.toString(R.drawable.icons) ); //?????? thay thế bằng hình thiệt trong db
				            hm.put("ten_game", ++count+ ". " + gameMoiNhat.getTTG_TEN_GAME());
				            hm.put("the_loai","Thể loại : " + gameMoiNhat.getTLG_TEN_THE_LOAI());
				            hm.put("luot_xem","Lượt xem: " + gameMoiNhat.getTTG_LUOT_XEM() + " Lượt tải: "+ gameMoiNhat.getTTG_LUOT_TAI());
				            hm.put("danh_gia","Đánh giá : " + gameMoiNhat.getDG_SODIEM());
				            aList.add(hm);
						  }
				        // Keys used in Hashmap
				        String[] from = {"icon", "ten_game","the_loai","luot_xem", "danh_gia" };
				        // Ids of views in listview_layout
				        int[] to = { R.id.icon,R.id.tengame,R.id.chude,R.id.luotxem,R.id.danhgia};
				        // Instantiating an adapter to store each items
				        // R.layout.listview_layout defines the layout of each item
				        SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.listview_layout, from, to);
				 
				        setListAdapter(adapter);
					}
				}
			}
		};

}
